#include "threadpool.h"
#include "BlockingQueue.hpp"

ThreadPool::ThreadPool(short threadnum)
{
    m_ptask_queue = std::make_unique<BlockingQueue<std::function<void()>>>();
    for (size_t i = 0; i < threadnum; i++)
    {
        //这里用到了线程的隐式转换构造
        m_workers.emplace_back([this]{worker();});
    }
}

ThreadPool::~ThreadPool()
{
    m_ptask_queue->Cancel();
    for (auto &worker: m_workers)
    {
        if (worker.joinable())
        {
            worker.join();
        }
    }
}

void ThreadPool::Post(std::function<void()> task)
{
    m_ptask_queue->Push(task);
}

void ThreadPool::worker()
{
    while (true)
    {
        std::function<void()> task;
        if (!m_ptask_queue->Pop(task))
        {
            break;
        }
        task();
    }
    
}
